package com.mall.search.mallsearch.controller;

import com.google.gson.JsonObject;
import com.mall.search.mallsearch.api.ResponseVo;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.core.search.aggregation.MetricAggregation;
import io.searchbox.core.search.aggregation.TopHitsAggregation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@Api(tags = "EsProductController", description = "搜索商品管理")
@RequestMapping("/esProduct")
public class EsProductController {

    @Autowired
    private JestClient jestClient;


    @GetMapping("/ESGroupSeriseName")
    @ApiOperation("ES聚合系列名称")
    public ResponseVo ESGroupSeriseNamea() throws Exception {

        SearchResult searchResult = null;
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder =
                AggregationBuilders.terms("categoryNameAgg").field("categoryName.keyword").size(10);
        searchSourceBuilder.aggregation(aggregationBuilder);
        Search search = ((io.searchbox.core.Search.Builder)((io.searchbox.core.Search.Builder)(new io.searchbox.core.Search.Builder(searchSourceBuilder.toString())).addIndex("modelgoods")).addType("modeldata")).build();
        searchResult = (SearchResult)jestClient.execute(search);
        MetricAggregation aggregations = searchResult.getAggregations();
        TopHitsAggregation categoryNameAgg = aggregations.getTopHitsAggregation("categoryNameAgg");
        JsonObject jsonObject = categoryNameAgg.getJsonObject();
        System.out.println(searchResult);


        return ResponseVo.success(jsonObject);
    }



}
